package com.chang.cheng.toutiaoserver.schedul;

import com.chang.cheng.toutiaoserver.utils.LocalDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;

import javax.servlet.ServletContext;;
import java.util.Enumeration;
import java.util.Objects;

@Component
public class ScheduleTask {
    @Autowired//ServletContext可以通过自动注入.
    private ServletContext servletContext;
    // 每隔10分钟执行一次
    @Scheduled(fixedRate = 6000000,initialDelay = 15000)//cron = "0/15 * * * * ?"
    public void printSay() {//定时任务不能有参数.
//        System.out.println("每隔15分钟清除一次：");
        assert servletContext != null;
        Enumeration<String> attributeNames = servletContext.getAttributeNames();
        while (attributeNames.hasMoreElements()){
            String key = attributeNames.nextElement();
            //这里有一些自带的键值,不是手机号
            try {
//                System.out.print("key: ");
//                System.out.println(key);
                Long.parseLong(key);
            } catch (NumberFormatException e) {
                continue;
            }
            Object attribute = servletContext.getAttribute(key);
            if(!(attribute instanceof String[])){
//                System.out.print("value: ");
//                System.out.println(attribute);
                continue;
            }
            String[] value=(String[])attribute;
            //键值对中值的第一数是时间
            Long preTime=Long.parseLong(value[0]);
            Long nowTime = LocalDateUtil.LDTToSecond();
            //超过5分钟的,手机号所对应的键值移除掉.
            if(nowTime-preTime>300){
                servletContext.removeAttribute(key);
            }
        }
    }

}
